package org.nf.web.param;

import cn.hutool.core.util.ReflectUtil;
import org.nf.web.annotation.Model;
import org.nf.web.common.TypeConverter;
import org.nf.web.servlet.MethodArgumentsResolver;
import org.nf.web.servlet.ServletApi;

import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.ServiceLoader;

/**
 * @Author czl
 * @Date 2024-05-20
 * 对象参数解析器
 */
public class ModelMethodArgumentResolver implements MethodArgumentsResolver {

    private final ServiceLoader<TypeConverter> loader = ServiceLoader.load(TypeConverter.class);

    @Override
    public boolean supports(Parameter parameter) {
        return parameter.isAnnotationPresent(Model.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) {
        //获取参数的Class类型
        Class<?> modelType = parameter.getType();
        //创建Model的实例
        Object instance = ReflectUtil.newInstance(modelType);
        //获取所有的私有字段
        Field[] fields = modelType.getDeclaredFields();
        for(Field field : fields) {
            //获取字段名称，这个名称需要和请求参数的name保持一致
            String fieldName = field.getName();
            //获取请求参数
            String value = servletApi.request().getParameter(fieldName);
            //获取字段的Class类型
            Class<?> fieldType = field.getType();
            for(TypeConverter converter : loader) {
                //如果支持则执行转换
                if(converter.supports(fieldType)) {
                    Object obj = converter.convert(value);
                    //将obj赋值给Field字段
                    field.setAccessible(true);
                    try {
                        field.set(instance, obj);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("Set field error. ", e);
                    }
                    break;
                }
            }
        }
        return instance;
    }
}